<!--
 * @Author: error: git config user.name && git config user.email & please set dead value or install git
 * @Date: 2022-06-15 11:10:35
 * @LastEditors: error: git config user.name && git config user.email & please set dead value or install git
 * @LastEditTime: 2022-06-17 10:34:58
 * @FilePath: \macc.admin.vue\src\components\rj-mqtt\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->

<script>
import * as mqtt from 'mqtt';
import { requestHttp, maccApi, ObjectUtil } from '@utils/index';
import { mapState } from 'vuex';
export default {
  name: 'RjMqtt',
  data() {
    return {
      client: null,
      connectInfo: null,
      options: {
        keepAlive: 40,
        clean: true, // true: 清除会话, false: 保留会话
        connectTimeout: 4000, // 超时时间
        // 认证信息
        clientId: null,
        username: null,
        password: null,
      },
      subscription: {
        topic: 'client/{accountId}/#',
        qos: 1,
      },
      subscribeSuccess: false,
    };
  },
  computed: {
    ...mapState('User', ['userInfo']),
  },
  watch: {
    userInfo: {
      async handler(n) {
        this.destroyConnection();
        this.init();
      },
      deep: true,
    },
  },
  created() {
    this.init();
  },

  methods: {
    async init() {
      console.log('开始创建VUE MQTT');
      await this.getMqttInfo();
      this.creatMqttConnect();
      this.doSubscribe();
    },
    async getMqttInfo() {
      const res = await requestHttp({
        api: maccApi.MQTT_CONNECTINFO_GET_API.replace(
          '{user_id}',
          this.userInfo?.accountId
        ),
        method: 'GET',
      });

      console.log('mqtt连接信息', res);
      if (res && res.code === 0) {
        const { clientid, username, key, serverList } = res;
        this.options.clientId = clientid;
        this.options.username = username;
        this.options.password = key;
        if (serverList.length == 1) {
          this.connectInfo = serverList[0];
        } else {
          for (let i = 0; i < serverList.length; i++) {
            if (serverList[i].protocol === 'wss') {
              this.connectInfo = serverList[i];
              break;
            }
          }
        }
      } else {
        this.$message.error(res.msg || this.$t('components.mqtt.getFail'));
      }
    },
    creatMqttConnect() {
      if (this.connectInfo) {
        const { connectUrl } = this.connectInfo;
        //this.client = mqtt.connect(connectUrl, this.options);
        try {
          this.client = mqtt.connect(connectUrl, this.options);
        } catch (error) {
          console.log('mqtt.connect error', error);
        }
        this.client.on('reconnect', (error) => {
          //console.log('正在重连:', error);
        });

        this.client.on('error', (error) => {
          console.log('连接失败:', error);
        });

        this.client.on('message', (topic, message) => {
          //const newMesage = self.Uint8ArrayToString(message);
          const msg = JSON.parse(message.toString());
          console.log('收到消息：', topic, message.toString());
          if (msg.msgType === 'USER_MSG') {
            //debugger;
            //判断是否为旧comted消息
            if (typeof msg.data === 'object') {
              const { type, content, title, isDisplay } = msg.data;
              if (isDisplay) {
                this.$notification['info']({
                  message: title,
                  description: content,
                });
              }

              if (
                ['GROUP_CHANGE', 'GROUP_NAME_CHANGED_EVENT'].indexOf(type) > -1
              ) {
                this.$store.dispatch('Group/getGroupTree');
              } else {
                if (ObjectUtil.isJSON(content)) {
                  this.$EventBus.$emit(type, JSON.parse(content));
                } else {
                  this.$EventBus.$emit(type, content);
                }
              }
            }
          } else {
            //新的mqtt消息
            const { msgType, data, title, isDisplay } = msg;
            if (isDisplay) {
              console.log('弹窗消息', data);
              this.$notification['info']({
                message: title,
                description: data,
              });
            }
            if (
              ['GROUP_CHANGE', 'GROUP_NAME_CHANGED_EVENT'].indexOf(msgType) > -1
            ) {
              this.$store.dispatch('Group/getGroupTree');
            } else {
              if (ObjectUtil.isJSON(data)) {
                this.$EventBus.$emit(msgType, JSON.parse(data));
              } else {
                this.$EventBus.$emit(msgType, data);
              }
            }
          }
        });
      }
    },
    doSubscribe() {
      const { topic, qos } = this.subscription;
      this.client.subscribe(
        topic.replace('{accountId}', this.userInfo?.accountId),
        qos,
        (error, res) => {
          if (error) {
            console.log('订阅消息失败', error);
            return;
          }
          this.subscribeSuccess = true;
          console.log('订阅返回信息', res);
        }
      );
    },
    destroyConnection() {
      if (this.client.connected) {
        try {
          this.client.end();
          this.client = null;
          console.log('MQTT断开连接成功');
        } catch (error) {
          console.log('MQTT断开连接失败', error.toString());
        }
      }
    },
  },

  destroyed() {
    this.destroyConnection();
  },
  render() {
    return <div style="display:none"></div>;
  },
};
</script>
